### This script will batch out calculations of yearly BIOCLIM values to multiple nodes

### Set location of script to run

script.file = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/ulCLIMyearlysummary/microCLIM_2run.r'

# Establish directory to write out .sh files to

tmp.pbs = '/home1/99/jc152199/tmp.pbs1/'
setwd(tmp.pbs)

for (i in c(1975:1985)) # This loop will create an .sh file with one argument for year

	{
		
		### Create name of .sh file
	
		tname = paste('microCLIM_',i,'.sh',sep='')
		
		### Create arguments
	
		arg.yearx = paste('yearx="',i,'" ',sep='') # Define the argument for year
	
		zz = file(tname,'w') # This command creates a file with the name 'tname' The 'w' command opens the file and writes the following lines of text into it
		
			cat('#!/bin/bash\n',file=zz) # First command line for HPC
			cat('cd $PBS_O_WORKDIR\n',file=zz) # Sets the directory to write out summary files at the above directory 'tmp.pbs'
			cat("R CMD BATCH --no-save --no-restore '--args ",arg.yearx,"' ",script.file,' ',gsub('.sh','',tname),'.Rout \n',sep='',file=zz) # This line tells R not to save to the .Rdata file and also not to restore the environment from the .Rdata file, very important when batching or you will get multiple fuckups, also defines the arguments, says where script to run is located, and defines the name for the R.out file
			
		close(zz) # Closes the .sh file that you've just written
	
		# The follow line submits the job to the HPC, leave it commented out until you're ready to RUN all the jobs\
		# Always run the script first without removing the comment, this will still generate the .sh files for you to check before running
		# Once you're happy with that then submit a single .sh file and make sure it runs through to completion before batching out the rest with the following line
	
		system(paste('qsub -m n -l nodes=1:ppn=8 ',tname,sep=''))
		system(paste('sleep 1s'))

	}
	
# Close loop

